package org.microframework.cloud.auth.config;

import org.microframework.cloud.auth.config.properties.SecurityIgnoreProperties;
import org.microframework.cloud.auth.handler.AuthenticationFailureHandlerImpl;
import org.microframework.cloud.auth.handler.AuthenticationSuccessHandlerImpl;
import org.microframework.cloud.auth.service.SecurityUserDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.web.SecurityFilterChain;

/**
 * 安全配置
 * 等保要求：应实现访问控制、安全审计等功能
 */
@Configuration
@EnableWebSecurity
public class SecurityConfig {
    
    @Autowired
    private SecurityUserDetailsService userDetailsService;
    
    @Autowired
    private AuthenticationSuccessHandlerImpl authenticationSuccessHandler;
    
    @Autowired
    private AuthenticationFailureHandlerImpl authenticationFailureHandler;
    
    @Autowired
    private SecurityIgnoreProperties ignoreProperties;
    
    /**
     * 默认安全配置
     * 等保要求：应实现最小权限原则
     */
    @Bean
    @Order(2)
    public SecurityFilterChain defaultSecurityFilterChain(HttpSecurity http) throws Exception {
        
        http
            // 禁用CSRF，因为使用JWT令牌认证
            .csrf(AbstractHttpConfigurer::disable)
            
            // 配置请求授权规则
            .authorizeHttpRequests(authorize -> {
                // 添加白名单请求放行
                ignoreProperties.getAllIgnoreUrls().forEach(url -> 
                    authorize.requestMatchers(url).permitAll()
                );
                // 其他请求需要认证
                authorize.anyRequest().authenticated();
            })
            
            // 配置表单登录
            .formLogin(form -> form
                .loginPage("/login")
                .loginProcessingUrl("/login")
                .successHandler(authenticationSuccessHandler)
                .failureHandler(authenticationFailureHandler)
                .permitAll()
            )
            
            // 配置登出
            .logout(logout -> logout
                .logoutUrl("/logout")
                .logoutSuccessUrl("/login?logout")
                .deleteCookies("JSESSIONID")
                .permitAll()
            )
            
            // 配置记住我功能
            .rememberMe(remember -> remember
                .key("microFrameworkAuthKey")
                .tokenValiditySeconds(86400) // 1天
                .userDetailsService(userDetailsService)
            )
            
            // 配置会话管理
            .sessionManagement(session -> session
                .maximumSessions(1) // 同一账号同时登录最大数量
                .maxSessionsPreventsLogin(false) // 达到最大会话数后，新登录会使旧会话失效
            );
        
        return http.build();
    }
} 